﻿using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Hicap.AuthorizationServer.Core.Common;
using Hicap.AuthorizationServer.Core.Domains.Sys.Notification;
using Hicap.AuthorizationServer.Core.Models.Sys;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;

namespace Hicap.AuthorizationServer.Core.Domains.Sys.Users
{
    /// <summary>
    /// User领域层的业务管理
    /// </summary>
    public class UsersManager : AuthorizationServerDomainServiceBase, IUsersManager
    {
        ////BCC/ BEGIN CUSTOM CODE SECTION
        ////ECC/ END CUSTOM CODE SECTION
        private readonly IRepository<User, int> _userRepository;

        private readonly IocManager _iocResolver;
        private readonly INotificationManager _notificationManager;

        /// <summary>
        /// User的构造方法
        /// </summary>
        public UsersManager(IRepository<User, int> userRepository, IocManager iocResolver, INotificationManager notificationManager)
        {
            _userRepository = userRepository;
            _iocResolver = iocResolver;
            _notificationManager = notificationManager;
        }

        public async Task NotificationUserActive(dynamic data)
        {
            await _notificationManager.Echo(NotificationType.UserActive, data);
        }

        public async Task NotificationUserForgetPassword(dynamic data)
        {
            await _notificationManager.Echo(NotificationType.UserForgetPassword, data);
        }

        [UnitOfWork]
        public async Task<int> Register(User user)
        {
            user.IsActive = false;

            int result = await _userRepository.InsertAndGetIdAsync(user);

            return result;
        }

        [UnitOfWork]
        public Task<User> ActiveUser(int id)
        {
            return Task.Run(() => _userRepository.Update(id, x => x.IsActive = true));
        }

        [UnitOfWork]
        public Task<User> FindByUserCode(string usercode)
        {
            return _userRepository.GetAllIncluding(x => x.SubordinateCompany).FirstOrDefaultAsync(x => x.UserCode.Equals(usercode));
        }

        public string GetPasswordSha256(string password)
        {
            return Encrypt.HmacSHA256(password, AuthorizationServerConsts.DefaultPassPhrase);
        }

        public bool CheckUserPassword(string inputPassword, User user)
        {
            return GetPasswordSha256(inputPassword).Equals(user.CurPassword);
        }
    }
}